﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace COC
{
	public partial class CoCGame
	{
		private KeyboardState m_CurrentKeyboardState;
		private MouseState m_CurrentMouseState;

		private KeyboardState m_LastKeyboardState;
		private MouseState m_LastMouseState;
		private bool bFirstInput = true;
		private List<Keys> lastKeys = new List<Keys>();

		public void HandleInput(GameTime gameTime)
		{
			m_LastKeyboardState = m_CurrentKeyboardState;
			m_CurrentKeyboardState = Keyboard.GetState();
			m_LastMouseState = m_CurrentMouseState;
			m_CurrentMouseState = Mouse.GetState();

			if (m_CurrentKeyboardState.IsKeyDown(Keys.Escape) &&
				!m_LastKeyboardState.IsKeyDown(Keys.Escape))
			{
				if (!m_Console.Activate)
				{
					Exit();
				}
				else
				{
					m_Console.Activate = false;
					return;
				}
			}

			if (m_CurrentKeyboardState.IsKeyDown(Keys.OemTilde) &&
				!m_LastKeyboardState.IsKeyDown(Keys.OemTilde))
			{
				m_Console.Activate = !m_Console.Activate;
			}

			if (m_Console.Activate)
			{
				foreach (Keys key in m_CurrentKeyboardState.GetPressedKeys())
				{
					if (!lastKeys.Contains(key))
					{
						m_Console.OnKeyDown(key,
							m_CurrentKeyboardState.IsKeyDown(Keys.LeftShift) ||
							m_CurrentKeyboardState.IsKeyDown(Keys.RightShift));
					}
				}
				lastKeys = m_CurrentKeyboardState.GetPressedKeys().ToList<Keys>();
				return;
			}

			if (bFirstInput)
			{
				bFirstInput = false;
				m_LastMouseState = m_CurrentMouseState;
			}

			Mouse.SetPosition(100, 100);

			float deltaX = m_CurrentMouseState.X - 100;// -m_LastMouseState.X;
			float deltaY = m_CurrentMouseState.Y - 100;// -m_LastMouseState.Y;

			float advanceVal = 0.0f, rightmovVal = 0.0f;
			if (m_CurrentKeyboardState.IsKeyDown(Keys.W))
			{
				advanceVal += (float)(0.05f * gameTime.ElapsedGameTime.TotalMilliseconds);
			}
			if (m_CurrentKeyboardState.IsKeyDown(Keys.S))
			{
				advanceVal += (float)(-0.05f * gameTime.ElapsedGameTime.TotalMilliseconds);
			}
			if (m_CurrentKeyboardState.IsKeyDown(Keys.A))
			{
				rightmovVal += (float)(-0.05f * gameTime.ElapsedGameTime.TotalMilliseconds);
			}
			if (m_CurrentKeyboardState.IsKeyDown(Keys.D))
			{
				rightmovVal += (float)(0.05f * gameTime.ElapsedGameTime.TotalMilliseconds);
			}

			bool isLBtnDown = (m_CurrentMouseState.LeftButton == ButtonState.Pressed);

			if (!m_GameWorld.UpdateActor(m_camera, advanceVal, rightmovVal,
				new Vector2(-deltaX * 0.005f, -deltaY * 0.005f), isLBtnDown))
			{
				m_camera.RotateAxisAngle(m_camera.Right, -deltaY * 0.005f);
				m_camera.RotateAxisAngle(new Vector3(0, 1, 0), -deltaX * 0.005f);
				m_camera.SetPosition(m_camera.Position
					+ m_camera.Direction * advanceVal
					+ m_camera.Right * rightmovVal);
			}
		}
	}
}